package com.leadingsoft.pwxk.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*import com.leadingsoft.pwxk.model.LatestData;
import com.leadingsoft.pwxk.model.QBaseInfo;
import com.leadingsoft.pwxk.model.QLicenseInfo;
import com.leadingsoft.pwxk.model.QPwBaseInfo;
import com.leadingsoft.pwxk.model.QSummary;
import com.leadingsoft.pwxk.model.QUndoBaseInfo;*/
import com.leadingsoft.pwxk.repository.LatestDataRepository;
import com.leadingsoft.pwxk.services.LatestDataService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class LatestDataServiceImpl implements LatestDataService {

/*
	private final QPwBaseInfo pwBaseInfo = QPwBaseInfo.pwBaseInfo;

	private final QBaseInfo baseInfo = QBaseInfo.baseInfo;

	private final QLicenseInfo licenseInfo = QLicenseInfo.licenseInfo;

	private final QUndoBaseInfo qUndoBaseInfo = QUndoBaseInfo.undoBaseInfo;

	QSummary qSummary = QSummary.summary;
*/

	@Autowired
	EntityManager em;
	@Autowired
	LatestDataRepository latestDataRepository;

	@Override
	@Transactional
	public void saveLatestData() {
		// 先删除最新数据
	/*	try {
			latestDataRepository.deleteAll();
			JPAQuery<Tuple> query = new JPAQuery<>(em);
			query.select(licenseInfo.dataid, pwBaseInfo.enterid);
			query.from(licenseInfo).leftJoin(pwBaseInfo).on(licenseInfo.dataid.eq(pwBaseInfo.dataid)).leftJoin(baseInfo)
					.on(pwBaseInfo.enterid.eq(baseInfo.enterid)).leftJoin(qSummary)
					.on(licenseInfo.dataid.eq(qSummary.dataid));
			JPAQuery<Tuple> query2 = new JPAQuery<>(em);
			// 去掉注销企业
			query.where(licenseInfo.dataid.notIn(query2.select(qUndoBaseInfo.dataid).from(qUndoBaseInfo)));
			// 通过Summary办结时间来确定去重取的是最新数据
			query.orderBy(qSummary.itemendtime.desc());
			List<Tuple> fetch = query.fetch();
			Map<String, LatestData> map = new HashMap<String, LatestData>();
			// 获取所有数据，处理去重
			fetch.forEach(t -> {
				if (null == map.get(t.get(pwBaseInfo.enterid))) {
					LatestData latestData = new LatestData();
					latestData.setDataid(t.get(licenseInfo.dataid));
					map.put(t.get(pwBaseInfo.enterid), latestData);
				}
			});
			for (LatestData t : map.values()) {
				latestDataRepository.save(t);
			}
		} catch (Exception e) {
			log.error("统计最新数据异常" + e.getMessage(), e);
		}*/

	}

}
